import type { userInfo } from '@/types/userInfo'
import { defineStore } from 'pinia'
import { ref } from 'vue'

const defaultUserInfoState: userInfo = {
  userName: '未登录',
  loginCode: '',
}
// 定义 Store
export const useInfoStore = defineStore(
  'userinfo',
  () => {
    // 用户信息
    const userState = ref<userInfo>(defaultUserInfoState)

    // 保存用户信息，登录时使用
    const setProfile = <T extends keyof userInfo>(key: T, val: userInfo[T]) => {
      userState.value[key] = val
    }

    // 清理会员信息，退出时使用
    const clearProfile = () => {
      userState.value = defaultUserInfoState
    }

    // 记得 return
    return {
      userState,
      setProfile,
      clearProfile,
    }
  },
  {
    // 网页端配置
    // persist: true,
    // 小程序端配置
    persist: {
      storage: {
        getItem(key) {
          return uni.getStorageSync(key)
        },
        setItem(key, value) {
          uni.setStorageSync(key, value)
        },
      },
    },
  },
)
